package com.myrent.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtil {
    /**
     * token密匙
     */
    public static String SECRET = "#!!!#$%#@@@!SD";


    public static String createToken(Integer userId,Integer shopId, String uuid) throws Exception {
        //签发时间
        Date signTime = new Date();
        //设置过期时间60min
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.DATE, 3);
        Date expiresDate = nowTime.getTime();
        Map<String, Object> map = new HashMap<>(2);
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        return JWT.create()
                .withHeader(map)
                .withClaim("userId", userId)
                .withClaim("shopId",shopId)
                .withClaim("uuid",uuid)
                .withExpiresAt(expiresDate)
                .withIssuedAt(signTime)
                .sign(Algorithm.HMAC256(SECRET));
    }


    public static Map<String, Claim> verifyToken(String token) throws Exception {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (Exception e) {
            return null;
        }
        return jwt.getClaims();
    }



}
